# Definition for singly-linked list.
import unittest
from typing import Optional


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]:
        head_r = self.reverse_list(head)
        j = 0
        cur = head_r
        tail = None

        while cur:
            add = cur.val * 2
            add += j
            cur.val = add % 10
            j = 1 if add > 9 else 0
            if not cur.next:
                tail = cur
            cur = cur.next

        if j == 1:
            tail.next = ListNode(1, None)
        return self.reverse_list(head_r)

    def reverse_list(self, head: Optional[ListNode]):
        if not head:
            return head
        pre = None
        cur = head
        while cur:
            nxt = cur.next
            cur.next = pre
            pre = cur
            cur = nxt
        return pre


class Test(unittest.TestCase):
    def test_case1(self):
        head = ListNode(1, ListNode(8, ListNode(9)))
        it = Solution().doubleIt(head)
        self.assertEqual(it.val, 3)
